import LivePlayer from '@/components/LivePlayer';
import { getWatchLive } from '@/services/WatchLiveSerivce';
import { useModel } from '@@/exports';
import { SettingOutlined, SyncOutlined } from '@ant-design/icons';
import { Collapse, CollapseProps, message } from 'antd';
import { useEffect, useState } from 'react';
import styles from './style.less';
import './styles.less';

type watchType = {
  id: number;
  title: string;
  name: string;
  livePath?: string;
  app?: string;
  stream?: string;
  type?: number;
  item: watchLiveListType[];
};
type watchLiveListType = {
  id?: number;
  title?: string;
  name?: string;
  livePath?: string;
  app?: string;
  stream?: string;
  type?: number;
};

const RightInput = ({
  liveClients,
  active,
  reloadOutList,
}: {
  liveClients: watchType[];
  active: (clientLive: watchLiveListType) => void;
  reloadOutList: () => void;
}) => {
  const activeOutput = async (client: watchLiveListType) => {
    active(client);
  };

  const items: CollapseProps['items'] = liveClients.map((client) => {
    return {
      key: client.id,
      label: (
        <div style={{ width: '100%', height: '100%' }}>
          <SettingOutlined style={{ marginRight: '10px' }} />
          {client.title}
        </div>
      ),
      children: client.item.map((clientItem, index) => {
        return (
          <div
            key={clientItem.id}
            onClick={async () => {
              await activeOutput(clientItem);
            }}
            style={{
              width: '100%',
              marginBottom: '5px',
              background: '#429eff',
              // borderRadius: '5px',
              height: '50px',
              display: 'flex',
              alignItems: 'center',
              paddingLeft: '10px',
            }}
          >
            {clientItem.name}
          </div>
        );
      }),
      style: {
        backgroundColor: '#429eff',
      },
    };
  });
  return (
    <div className={styles.leftInput}>
      <div className={styles.topSearch}>
        <div className={styles.label}>直播列表</div>
        <div className={styles.refresh}>
          <SyncOutlined onClick={() => reloadOutList()} />
        </div>
      </div>
      <div>
        <Collapse
          className={styles.collapseCus}
          style={{ height: '100%' }}
          defaultActiveKey={'1'}
          accordion={true}
          expandIconPosition={'end'}
          items={items}
        />
      </div>
    </div>
  );
};

const CenterVideo = ({ activeLives }: { activeLives: any }) => {
  const [visible, setVisible] = useState(true);
  const { initialState } = useModel('@@initialState');
  console.log('activeLives', activeLives);
  return (
    <>
      {activeLives && activeLives.type == 2 && (
        <div className={styles.CenterVideoBox}>
          <LivePlayer
            server={activeLives.livePath}
            streamKey={'main'}
            type="Encoder_WebRTC"
            visible={visible}
            controls={false}
            muted={false}
          />
        </div>
      )}
      {activeLives && activeLives.type == 1 && (
        <div className={styles.CenterVideoBox}>
          <LivePlayer
            server={initialState!.obsPushServer}
            streamKey={activeLives.app + '/' + activeLives.stream}
            type="Costomer_WebRTC"
            visible={visible}
            controls={false}
            muted={false}
          />
        </div>
      )}
      {!activeLives && (
        <div className={styles.CenterVideoBox}>
          <div className={styles.centerVideo}>未选择设备</div>
        </div>
      )}
    </>
  );
};

export default () => {
  const { peerServer } = useModel('global');
  const [inLiveClients, setInLiveClients] = useState<watchType[]>([]);
  const [outLiveClients, setOutLiveClients] = useState<watchType[]>([]);
  const [isPlay, setIsPlay] = useState<boolean>(false);
  const [activeLive, setActiveLive] = useState<watchLiveListType>(null);
  const [_message, contextHolder] = message.useMessage();

  const [inputDrag, setInputDrag] = useState<boolean>(false);

  async function getDeviceList(setList: (client: watchType[]) => void) {
    const result = await getWatchLive(peerServer);
    console.log('getOutputList', result);
    if (result.success) {
      const deviceList = convertDevice(
        result.data,
        (item, after) => item.id === after.id,
        (after) => {
          return {
            id: after.id,
            title: after.title,
            name: after.name,
            item: [{ ...after }],
          };
        },
      );
      setList(deviceList);
    } else {
      setList([]);
    }
  }

  useEffect(() => {
    getDeviceList(setInLiveClients);
  }, []);
  useEffect(() => {
    setIsPlay(false);
    setTimeout(() => {
      setIsPlay(true);
    }, 200);
  }, [activeLive]);

  const convertDevice = (
    list: watchLiveListType[],
    findFuc: (item: watchLiveListType, after: watchLiveListType) => boolean,
    pushFuc: (after: watchLiveListType) => watchType,
  ): watchType[] => {
    return list.reduce((pre, after) => {
      const index = pre.findIndex((item) => findFuc(item, after));
      if (index === -1) {
        pre.push(pushFuc(after));
      } else {
        pre[index].item.push(after);
      }
      return pre;
    }, []);
  };
  return (
    <div className={styles.liveVideo}>
      {contextHolder}
      <RightInput
        liveClients={inLiveClients}
        active={setActiveLive}
        reloadOutList={() => {
          if (activeLive) {
            setActiveLive(null);
          }
          getDeviceList(setOutLiveClients);
        }}
      />
      <CenterVideo activeLives={activeLive} />
    </div>
  );
};
